package com.wst.system.controller;

import com.alibaba.fastjson2.JSONObject;
import com.wst.system.config.Constant;
import com.wst.system.security.SelfUserDetailsService;
import com.wst.system.security.config.JWTConfig;
import com.wst.system.security.entity.SelfUserEntity;
import com.wst.system.security.entity.SysRoleEntity;
import com.wst.system.security.entity.SysUserTokenEntity;
import com.wst.system.server.service.SysUserService;
import com.wst.system.server.service.SysUserTokenService;
import com.wst.system.util.JWTTokenUtil;
import com.wst.system.util.ResultUtil;
import com.wst.system.util.SecurityUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.*;

@Api(tags = {"token服务"})
@RestController
@RequestMapping("token")
public class SysTokenController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SelfUserDetailsService userDetailsService;

    @Autowired
    private SysUserTokenService sysUserTokenService;

    @PreAuthorize("hasAnyRole('flush_token')")
    @GetMapping(Constant.REFLUSH_TOKEN_URL)
    public JSONObject relushToken(HttpServletRequest request,
                                  HttpServletResponse response) {
        SelfUserEntity user= SecurityUtil.getUserInfo();
        Set<GrantedAuthority> authorities = new HashSet<>();
        SelfUserEntity userInfo = userDetailsService.loadUserByUsername(user.getUsername());
        // 查询用户角色
        List<SysRoleEntity> sysRoleEntityList = sysUserService.selectSysRoleByUserId(user.getUserId());
        if(sysRoleEntityList!=null && sysRoleEntityList.size()>0) {
            for (SysRoleEntity sysRoleEntity : sysRoleEntityList) {
                authorities.add(new SimpleGrantedAuthority("ROLE_" + sysRoleEntity.getRoleName()));
            }
            userInfo.setAuthorities(authorities);
        }
        String token=JWTTokenUtil.createAccessToken(userInfo);
        token = JWTConfig.tokenPrefix + token;

        SysUserTokenEntity userToken=new SysUserTokenEntity();
        userToken.setUserid(userInfo.getUserId().toString());
        userToken.setUsername(userInfo.getUsername());
        userToken.setLogindate(new Date());
        userToken.setIsDisabled(true);
        userToken.setToken(token);
        userToken.setTokenType(Constant.USER_TOKEN);
        sysUserTokenService.save(userToken);

        Map<String,Object> resultData = new HashMap<>();
        resultData.put(Constant.USER_TOKEN,token);
        Cookie cookie = new Cookie(JWTConfig.tokenHeader, token);
        // 设置Cookie的其他属性（可选）
        cookie.setMaxAge(3600); // 设置Cookie的生命周期，单位为秒
        cookie.setPath("/"); // 设置Cookie的路径
        // 其他属性，如：cookie.setDomain("domain.com");
        // 将Cookie添加到响应中
        response.addCookie(cookie);
        return ResultUtil.successInfo(resultData);
    }

}
